package _4Game;

import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.JPanel;

public class GameClient 
{
	// 服务器地址
	String host = "127.0.0.1";
	// 服务器端口
	int port= 8888;
	
	// 聊天窗口对象
	GameClientFrame f;
	
	// 套接字
	Socket s;
	
	// 发送信息
	public void send(int d)
	{

		try {
			// 得到输出流			
			OutputStream out = s.getOutputStream();
			// 发送内容
			out.write(d);
		} catch (IOException e) 
		{
//			f.showMsg("出错了:"+e.getMessage());
		}
	}
	
	// 连接服务器
	public void connect()
	{
		// 开启一个子线程,在子线程中连接服务器,不卡住界面
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
//				f.showMsg("连接"+host+":"+port);
				try {
					s = new Socket(host,port);
				} catch (UnknownHostException e) {
//					f.showMsg("出错了"+e.getMessage());
					return;
				} catch (IOException e) {
//					f.showMsg("出错了"+e.getMessage());
					return;
				}		
//				f.showMsg("连接成功");
				
				
				// 读取数据
				// 从socket得到输入流
				ObjectInputStream in;
				try {
					in = new ObjectInputStream(s.getInputStream());
					
					while(true)
					{
						ArrayList<Snake> snakes;
						try {
							int x = (Integer)in.readObject();
							System.out.println(x);
							snakes = (ArrayList<Snake>)in.readObject();
							System.out.println(snakes);							
							f.showSnakes(snakes);
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					
					}
					
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				


				
				
			}
		});
		t.start();
		
	}

}

//java.io.StreamCorruptedException: invalid type code: AC
//at java.io.ObjectInputStream.readObject0(Unknown Source)
//at java.io.ObjectInputStream.readObject(Unknown Source)
//at _4Game.GameClient$1.run(GameClient.java:70)
//at java.lang.Thread.run(Unknown Source)
